// pages/service/ask_service.js
const api = require("../request/api")
const request = require("../request/request")
const util = require("../utils/util")
const App = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        barHeight: App.globalData.paddingTop,
        styledata: {
            "bg_color": "white",
            "color": "#000",
            "leftflag": true,
            // "homeflag": true,
            "name": "申请售后"
        },

        uid: '',
        oid: '',
        trade_no: '',
        noteValue: '',
        // 退款金额
        RMamount: '',
        // 实付金额
        real_amount: '',

        // 申请类型 原因
        typetext: {
            text: '点击选择申请类型',
            value: -1
        },
        reasontext: {
            text: '点击选择申请原因',
            value: -1
        },

        typechoice: [
            {
                text: '我要退款',
                value: 0,
                type: 1
            },
            {
                text: '我要退货退款(未收到货)',
                value: 1
            },
            {
                text: '我要退货退款',
                value: 2
            },
            {
                text: '我要换货',
                value: 3
            },
        ],

        reasonchoice: [
            {
                text: '不想要了',
                value: 0
            },
            {
                text: '忘记使用优惠券',
                value: 1
            },
            {
                text: '货物与描述不符',
                value: 2
            },
            {
                text: '质量问题',
                value: 3
            },
            {
                text: '商家发错货',
                value: 4
            },
            {
                text: '其他原因',
                value: 5
            },
        ],

        typevisible: false,
        reasonvisible: false,

        // 详细说明字数
        fontnum: 150,

        // 图片上传相关
        originFiles: [
            // {
            //     url: 'https://tdesign.gtimg.com/miniprogram/images/example4.png',
            //     name: 'uploaded1.png',
            //     type: 'image',
            // },
            // {
            //     url: 'https://tdesign.gtimg.com/miniprogram/images/example6.png',
            //     name: 'uploaded2.png',
            //     type: 'image',
            // },
            // {
            //     url: 'https://tdesign.gtimg.com/miniprogram/images/example5.png',
            //     name: 'uploaded1.png',
            //     type: 'image',
            // },
        ],
        // 每行上传图片列数以及图片的宽度和高度
        gridConfig: {
            column: 4,
            width: 120,
            height: 120,
        },
        config: {
            count: 1,
        },
        howtall: 20
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let { oid, trade_num, real_pay } = options
        this.setData({
            uid: App.globalData.uid,
            oid,
            trade_no: trade_num,
            RMamount: real_pay,
            real_amount: real_pay
        })
    },

    // 提交售后申请
    async submitApply() {
        util.showLoading('申请提交中')
        let typevalue = this.data.typetext.value
        let reasonvalue = this.data.reasontext.value

        if (typevalue == -1) {
            return util.showToast('请选择售后类型')
        } else if (typevalue == 1 || typevalue == 2) {
            return util.showToast('退货退款功能升级中，请先联系客服')
        } else if (typevalue == 3) {
            return util.showToast('换货功能升级中，请先联系客服')
        }

        if (reasonvalue == -1) {
            return util.showToast('申请原因不能为空')
        }

        let data = {
            user_id: this.data.uid,
            source_id: this.data.oid,
            ctype: this.data.typetext.type,
            trade_no: this.data.trade_no,
            content: this.data.reasontext.value == -1 ? '' : this.data.reasontext.text,
            title: this.data.noteValue,
            amount: this.data.RMamount
        }

        // 上传图片拿到存放地址
        let pathARR = this.data.originFiles
        let imgUrl = []
        for (let i = 0; i < pathARR.length; i++) {
            let path = pathARR[i].url
            let uploadRes = await this.uploadTemPhoto(path)
            if (uploadRes.code == 0) {
                imgUrl.push(uploadRes.data.url)
            }
        }

        data.img_list = imgUrl.length == 0 ? '' : imgUrl.join(',')
        // console.log('data', data);

        let res = await request.postall(api.suggestadd, data)
        console.log(res);
        util.hideLoading()
        // console.log(res); 
        if (res.code == 0) {
            util.showSuccess('已成功提交')
            let timer = setTimeout(() => {
                wx.navigateBack({
                    delta: 1
                });
                clearTimeout(timer)
            }, 1500);
        }
    },

    // 键入退款金额
    inputAmount(e) {
        let real_amount = this.data.real_amount
        let inputvalue = e.detail.value

        if (inputvalue > real_amount) {
            let timer = setTimeout(() => {
                this.setData({
                    RMamount: real_amount
                })
                clearTimeout(timer)
            }, 1000);
            return util.showToast('退款金额不能大于订单实付金额')
        }
        // console.log(inputvalue);
        this.setData({
            RMamount: inputvalue
        })
    },

    //申请类型勾选
    typeChange(event) {
        const { value } = event.detail;
        // 取消使用
        if (this.data.typetext.value == value) {
            this.setData({
                typetext: {
                    text: '点击选择申请类型',
                    value: -1
                },
                typevisible: false
            });
            return
        }
        this.setData({
            typetext: this.data.typechoice[value],
            typevisible: false
        });
    },

    //申请原因勾选
    reasonChange(event) {
        const { value } = event.detail;
        // 取消使用
        if (this.data.reasontext.value == value) {
            this.setData({
                reasontext: {
                    text: '点击选择申请原因',
                    value: -1
                },
                reasonvisible: false
            });
            return
        }
        this.setData({
            reasontext: this.data.reasonchoice[value],
            reasonvisible: false
        });
    },

    // 点击查看弹出
    typePopup(e) {
        this.setData(
            { typevisible: true }
        );
    },
    reasonPopup(e) {
        this.setData(
            { reasonvisible: true }
        );
    },

    // 点击遮罩层去隐藏弹出层
    onVisibleChange(e) {
        this.setData({
            typevisible: e.detail.visible,
            reasonvisible: e.detail.visible
        });
    },

    // 记录备注
    inputHandler(e) {
        let str = e.detail.value
        let strlength = str.length
        // console.log(str, strlength);
        this.setData({
            noteValue: str,
            fontnum: 150 - strlength
        })
    },

    taller() {
        this.setData({
            howtall: 40
        })
        wx.pageScrollTo({
            scrollTop: 1000
        })
        // console.log('taller', this.data.howtall);
    },
    resettall() {
        this.setData({
            howtall: 20
        })
        // console.log('resettall', this.data.howtall);
    },

    // 图片上传相关方法
    handleSuccess(e) {
        const { files } = e.detail;
        this.setData({
            originFiles: files,
        });
    },
    handleRemove(e) {
        const { index } = e.detail;
        const { originFiles } = this.data;
        originFiles.splice(index, 1);
        this.setData({
            originFiles,
        });
    },
    handleClick(e) {
        console.log(e.detail.file);
    },

    // 将临时图片上传到小程序后台服务器
    async uploadTemPhoto(photoUrl) {
        return new Promise((resolve, reject) => {
            wx.uploadFile({
                url: api.upload_photo, // 已切换韦总接口真实地址
                filePath: photoUrl, // 临时地址，并非真正图片的路径
                name: 'imgFile',
                success(res) {
                    // console.log(res);
                    const data = JSON.parse(res.data)
                    // console.log(data);
                    resolve(data)
                    // if (data.code == 0) {
                    //     that.set_avatar(data.data.url)
                    //     util.showToast("头像保存成功")
                    // } else {
                    //     util.showToast("头像保存失败！")
                    // }
                },
                fail(err) {
                    resolve(err)
                }
            })
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})